__author__ = 'guo'


from extends.BaseHandle import BaseHandle
import json


class UploadFile(BaseHandle):

    def get(self, *args, **kwargs):
        data = ''
        data['code'] = 200
        data['message'] = '你好'
        return self.api_response(data)

    def post(self, *args, **kwargs):
        import os
        upload_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static/articleImg')  #文件的暂存路径
        file_metas = self.request.files['wpuf_file']    #提取表单中‘name’为‘file’的文件元数据

        import time
        for meta in file_metas:
            filename = str(int(time.time()))+"_"+meta['filename']
            filepath = os.path.join(upload_path, filename)
            with open(filepath, 'wb') as up:      #有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
            # imgStr = '<img width="200" height="460" src="/static/articleImg/'+filename+'" class="attachment-medium" alt="100" />'
            self.write("/static/articleImg/"+filename)

    def put(self, *args, **kwargs):
        data = ''
        data['code'] = 200
        data['message'] = '你好'
        return json.dump(data)


# 其它页面
class Other(BaseHandle):
    def get(self):
        returnjson = ""
        if self.get_argument("action", "None") == "config":
            ueconfig = {}
            ueconfig["imageActionName"] = "uploadimage"
            ueconfig["imageFieldName"] = "upfile"
            ueconfig["imageMaxSize"] = 2048000
            ueconfig["imageAllowFiles"] = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
            ueconfig["imageCompressEnable"] = "true"
            ueconfig["imageCompressBorder"] = 1600
            ueconfig["imageInsertAlign"] = "none"
            ueconfig["imageUrlPrefix"] = ""
            ueconfig["imagePathFormat"] = "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"
            returnjson = ueconfig
            self.api_response(returnjson)
        elif self.get_argument("action", "None") == "uploadimage":
            # from PIL import Image
            # try:
            #         reqfile = request.FILES['picfile']#picfile要和html里面一致
            #         img = Image.open(reqfile)
            #         img.thumbnail((500,500),Image.ANTIALIAS)#对图片进行等比缩放
            #         img.save("/Users/bcc/Desktop/python/bbs/Image/a.png","png")#保存图片
            # except Exception as e:
            #        return HttpResponse("Error %s"%e)#异常，查看报错信息

            test = {}
        else:
            self.render("404.html")
        # raise tornado.web.HTTPError(status_code=416, log_message="tes", reason="unkonw request")


